package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrResponseVo;
import com.atguigu.gulimall.search.vo.BrandVo;
import com.atguigu.gulimall.search.vo.SearchParamVo;
import com.atguigu.gulimall.search.vo.SearchResultVo;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 检索功能
 *
 * @author LaiSanShan
 * @date 2021-08-11
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    /**
     * 检索
     *
     * @param paramVo 检索参数
     * @return 检索结果
     */
    @Override
    public SearchResultVo search(SearchParamVo paramVo) {
        // 封装请求
        SearchRequest searchRequest = buildSearchRequest(paramVo);

        // 执行es查询
        SearchResponse response;
        try {
            response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            // 解析查询结果
            SearchResultVo res = buildSearchResult(paramVo, response);
            return res;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 解析查询结果,封装成响应数据
     *
     * @param response 查询结果
     * @return 检索结果
     */
    private SearchResultVo buildSearchResult(SearchParamVo paramVo, SearchResponse response) {
        SearchResultVo searchResultVo = new SearchResultVo();
        // 1.返回查询到的所有商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> products = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel sku = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (StringUtils.isNotBlank(paramVo.getKeyword())) {
                    // 获取高亮
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    sku.setSkuTitle(skuTitle.getFragments()[0].string());
                }
                products.add(sku);
            }
        }
        searchResultVo.setProducts(products);

        // 2.当前所有商品涉及到的所有属性信息
        List<SearchResultVo.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            // 获取属性id
            SearchResultVo.AttrVo attrVo = new SearchResultVo.AttrVo();
            Long attrId = Long.valueOf(bucket.getKeyAsString());
            attrVo.setAttrId(attrId);

            // 获取属性名
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attr_name = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attr_name);

            // 获取属性值
            List<String> values = new ArrayList<>();
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            for (Terms.Bucket attr_value_aggBucket : attr_value_agg.getBuckets()) {
                String keyAsString1 = attr_value_aggBucket.getKeyAsString();
                values.add(keyAsString1);
            }
            attrVo.setAttrValue(values);
            attrVos.add(attrVo);
        }

        searchResultVo.setAttrs(attrVos);

        // 3.当前所有商品涉及到的所有品牌信息
        List<SearchResultVo.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            // 获取品牌id
            SearchResultVo.BrandVo brandVo = new SearchResultVo.BrandVo();
            String keyAsString = bucket.getKeyAsString();
            brandVo.setBrandId(Long.valueOf(keyAsString));

            // 获取品牌名
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brand_name = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brand_name);

            // 获取图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brand_img = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brand_img);

            brandVos.add(brandVo);
        }

        searchResultVo.setBrands(brandVos);

        // 4.当前所有商品涉及到的所有分类信息
        List<SearchResultVo.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> catalog_aggBuckets = catalog_agg.getBuckets();
        for (Terms.Bucket catalog_aggBucket : catalog_aggBuckets) {
            // 获取分类id
            SearchResultVo.CatalogVo catalogVo = new SearchResultVo.CatalogVo();
            String keyAsString = catalog_aggBucket.getKeyAsString();
            catalogVo.setCatalogId(Long.valueOf(keyAsString));

            // 获取分类名
            Aggregations bucketAggregations = catalog_aggBucket.getAggregations();
            ParsedStringTerms catalog_name_agg = bucketAggregations.get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);

            catalogVos.add(catalogVo);
        }
        searchResultVo.setCatalogs(catalogVos);

        // 5.分页信息-页码
        searchResultVo.setPageNum(paramVo.getPageNum());

        // 6.分页信息-总记录数
        long total = hits.getTotalHits().value;
        searchResultVo.setTotal(total);

        // 7.分页信息-总页码
        int totalPages = (int) (total % EsConstant.PRODUCT_PAGESIZE == 0 ? total / EsConstant.PRODUCT_PAGESIZE : total / EsConstant.PRODUCT_PAGESIZE + 1);
        searchResultVo.setTotalPages(totalPages);

        // 8.分页信息-可遍历页码
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        searchResultVo.setPageNavs(pageNavs);

        // 9.构建面包屑导航功能
        if (!CollectionUtils.isEmpty(paramVo.getAttrs())) {
            List<SearchResultVo.NavVo> navVos = paramVo.getAttrs().stream().map(attr -> {
                SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
                String[] s = attr.split("_");
                Long attrId = Long.valueOf(s[0]);
                // 保存被选中属性id
                searchResultVo.getAttrIds().add(attrId);
                // 远程获取属性名
                R r = productFeignService.info(attrId);
                if (r.getCode() == 0) {
                    AttrResponseVo attrResponseVo = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setName(attrResponseVo.getAttrName());
                } else {
                    navVo.setName(s[0]);
                }

                // 获取属性值
                navVo.setNavValue(s[1]);

                // 获取要跳转的url，url会被编码
                String replace = replaceQueryString(paramVo.get_queryString(), attr, "attrs");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                return navVo;
            }).collect(Collectors.toList());
            searchResultVo.setNavs(navVos);
        }
        // 品牌、分类也加到面包屑导航中
        if (!CollectionUtils.isEmpty(paramVo.getBrandId())) {
            List<SearchResultVo.NavVo> navs = searchResultVo.getNavs();
            SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
            navVo.setName("品牌");
            // 获取品牌名
            R r = productFeignService.listByIds(paramVo.getBrandId());
            if (r.getCode() == 0) {
                List<BrandVo> voList = r.getData("brand", new TypeReference<List<BrandVo>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String replace = "";
                for (BrandVo brandVo : voList) {
                    buffer.append(brandVo.getBrandName() + ";");
                    replace = replaceQueryString(paramVo.get_queryString(), brandVo.getBrandId().toString(), "brandId");
                }
                navVo.setNavValue(buffer.toString());
                // 获取跳转的url
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
            }
            navs.add(navVo);
            searchResultVo.setNavs(navs);
        }

        return searchResultVo;
    }

    /**
     * 替换attr
     *
     * @param _queryString url地址
     * @param value        替换的值
     * @return 替换后的url
     */
    private String replaceQueryString(String _queryString, String value, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            // 浏览器差异化处理，空格编码格式+与20%
            encode = encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return _queryString.replace("&" + key + "=" + encode, "");
    }

    /**
     * 构建检索请求
     *
     * @return 检索请求
     */
    private SearchRequest buildSearchRequest(SearchParamVo paramVo) {
        // 构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 1.查询：模糊匹配、过滤
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1 关键字匹配
        if (StringUtils.isNotBlank(paramVo.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", paramVo.getKeyword()));
        }
        // 1.2.1 三级分类匹配
        if (paramVo.getCatalogId() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", paramVo.getCatalogId()));
        }
        // 1.2.2 品牌id匹配
        if (!CollectionUtils.isEmpty(paramVo.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", paramVo.getBrandId()));
        }
        // 1.2.3 属性id匹配
        if (!CollectionUtils.isEmpty(paramVo.getAttrs())) {
            for (String attr : paramVo.getAttrs()) {
                BoolQueryBuilder query = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                query.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                query.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", query, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        // 1.2.4 是否有库存匹配
        if (paramVo.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", paramVo.getHasStock() == 1));
        }
        // 1.2.5 价格区间匹配
        if (StringUtils.isNotBlank(paramVo.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = paramVo.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1 && paramVo.getSkuPrice().startsWith("_")) {
                rangeQuery.lte(s[0]);
            } else if (s.length == 1 && paramVo.getSkuPrice().endsWith("_")) {
                rangeQuery.gte(s[0]);
            }
            boolQuery.filter(rangeQuery);
        }
        sourceBuilder.query(boolQuery);

        // 2.排序、分页、高亮
        // 2.1 排序
        if (StringUtils.isNotBlank(paramVo.getSort())) {
            String[] s = paramVo.getSort().split("_");
            SortOrder order = "asc".equalsIgnoreCase(s[1]) ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }
        // 2.2 分页
        if (paramVo.getPageNum() != null && paramVo.getPageNum() > 0) {
            sourceBuilder.from((paramVo.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        } else {
            sourceBuilder.from(0);
        }
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        // 2.3 高亮
        if (StringUtils.isNotBlank(paramVo.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        // 3.聚合分析
        // 3.1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        // 3.2 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        // 3.3 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);

        System.out.println("DSL：" + sourceBuilder.toString());
        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
    }

}
